﻿CREATE FUNCTION [dbo].[yaf_forum_posts]
               (@ForumID INT)
RETURNS INT
AS
  BEGIN
	DECLARE  @NumPosts INT
		DECLARE  @tmp INT
		SELECT @NumPosts = NumPosts
		FROM   dbo.yaf_Forum
		WHERE  ForumID = @ForumID
		IF EXISTS (SELECT 1
					FROM   dbo.yaf_Forum
					WHERE  ParentID = @ForumID)
		BEGIN
			DECLARE c CURSOR  FOR
				SELECT ForumID
				FROM   dbo.yaf_Forum
				WHERE  ParentID = @ForumID
				OPEN c
				FETCH NEXT FROM c
				INTO @tmp
				WHILE @@FETCH_STATUS = 0
				BEGIN
					SET @NumPosts = @NumPosts + dbo.Yaf_forum_posts(@tmp)
						FETCH NEXT FROM c
						INTO @tmp
					END
				CLOSE c
				DEALLOCATE c
			END
		RETURN @NumPosts
	END


